var express = require('express');
var router = express.Router();
var fs = require("fs");
var path = require("path");

router.post('/open', function(req, res, next) {
	res.json({ status: 'success' });
});

router.post('/save', function(req, res, next) {debugger;
	res.json({ status: 'success' });
});

router.get('/graphs', function(req, res, next) {debugger;
    var root = path.resolve(__dirname, '../xmls');
    fs.readdir(root, function(err, files){   
        if(!files) {
          res.json({ status: 'success', data: [] });
          return;
        }

        var data = [];
        for(var i=0;i<files.length;i++) {
            var f = files[i];
            let _id = f.split('.')[0];
            let _name = f.split('.')[1];
            data.push({id: _id, name: _name});
        }
        res.json({ status: 'success', data: data });
    })
});

router.get('/graphs/:id', function(req, res, next) {
	var root = path.resolve(__dirname, '../xmls');
	fs.readdir(root, function(err, files){   
    if(!files) {
      res.json({ status: 'error', data: 'no file in xmls dir' });
      return;
    }

    var isFound = false;
    for(var i=0;i<files.length;i++) {
    	var f = files[i];
    	let _id = f.split('.')[0];
        let _name = f.split('.')[1];
    	if(req.params.id == _id) {
    		isFound = true;
    		console.log("file: " + f + " is matched.");
    		fs.readFile( root + '/' + f, function (err, data) {
					if (err) {
				    console.error(err);
				    res.json({ status: 'error', data: err });
					}
					res.json({ status: 'success', data: {id: _id, name: _name, xml: data.toString()} });
				});
    		break;
    	}
    }
    if(!isFound) {
    	res.json({ status: 'error', data: 'not found with id: ' + req.params.id });
    }      
  })

});

router.put('/graphs/:id', function(req, res, next) {
    var root = path.resolve(__dirname, '../xmls');

    var _id = req.params.id;
    var _name = req.body.name;
    var _xml = req.body.xml;

    var fileName = _id + '.' + _name + '.xml'
    fs.writeFile(root + '/' + fileName, _xml, 'utf-8', (err) => {
        if(err) {
            res.json({ status: 'error', data: err});
        } else {
            res.json({ status: 'success'});
        }
    })

});

module.exports = router;
